﻿using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;


public class TimingTaskManager : MonoBehaviour
{
    private Dictionary<TimingTaskType, TimingTask> tasks = new Dictionary<TimingTaskType, TimingTask>();
    private List<TimingTaskType> invalidTasks = new List<TimingTaskType>();

    public void Add(TimingTaskType id,Action action,long time)
    {
        tasks[id] = new TimingTask(id,action,time);
    }

    public void Delete(TimingTaskType id)
    {
        tasks.Remove(id);
    }

    public void ResetTime(TimingTaskType id,long time)
    {
        if(!tasks.ContainsKey(id))
        {
            Debug.LogError("TaskType:" + id + "Not exist");
        }
        else
        {
            tasks[id].time = time;
        }
    }

    public void Clear()
    {
        tasks.Clear();
    }
    void Update()
    {
        if (tasks.Count == 0)
        {
            return;
        }
        long totalTime = ServerTimerTool.CurrentUTCJavaTime();


        var it = tasks.GetEnumerator();      
        while(it.MoveNext())
        {
           if( it.Current.Value.time < totalTime)
            {
                it.Current.Value.action();
                invalidTasks.Add(it.Current.Key);                              
            }
        }
        if(invalidTasks.Count == 0)
        {
            return;
        }
        for(int i = 0; i<invalidTasks.Count;++i)
        {
            tasks.Remove(invalidTasks[i]);
        }
        invalidTasks.Clear();
    }


    private static TimingTaskManager instance;
    public static TimingTaskManager Instance
    {
        get
        {
            return instance;
        }
    }

    void Awake()
    {
        instance = this;
    }
}

public class TimingTask
{
    public long time = 0;
    public Action action;
    public TimingTaskType id;
    public TimingTask(TimingTaskType id,Action action,long time)
    {
        this.id = id;
        this.action = action;
        this.time = time;
    }
}
public enum TimingTaskType
{
    LIGHT_CHURCH = 0,
}